//
//  ComposeViewController.swift
//  Weibo
//
//  Created by apple on 15/7/7.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 微博文字的最大长度
private let statusMaxLength = 140

class ComposeViewController: UIViewController,UITextViewDelegate {
    
    /// 表情键盘控制器
    private lazy var emoticonKeyboardVC: EmoticonViewController = EmoticonViewController { [unowned self] (emoticon)  in
        self.textView.insertEmoticon(emoticon)
    }
    
    ///  切换表情视图
    func inputEmoticon() {
        // 如果输入视图是 nil，说明使用的是系统键盘
        print(textView.inputView)
        
        // 要切换键盘之前，需要先关闭键盘
        textView.resignFirstResponder()
        
        // 更换键盘输入视图
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboardVC.view : nil
        
        // 重新设置焦点
        textView.becomeFirstResponder()
    }
    //关闭控制器方法close
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
///  发送微博方法
    func sendStatus(){
        
        if textView.emoticonText().characters.count < 0 {
            return
        }
        if textView.emoticonText().characters.count > statusMaxLength{
            SVProgressHUD.showErrorWithStatus("字符过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        NetworkTools.sharedNetworkTools().postStatus(textView.emoticonText()) { (error) -> () in
            if error != nil{
                    SVProgressHUD.showErrorWithStatus("您的网络出问题了", maskType: SVProgressHUDMaskType.Black)
                    return
            }
        }
        self.close()
    }
    ///  textview 代理方法
   
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //判断文字长度
        let len = statusMaxLength - textView.emoticonText().characters.count
        lengthLabel.text = (len == 0) ? "" : String(len)
        lengthLabel.textColor = len > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
    override func viewWillAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        textView.resignFirstResponder()
    }
    
///  加载视图
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        addChildViewController(emoticonKeyboardVC)
        prepareNavigationBar()
        
        prepareTextView()
        
       prepreaOthers()
    }
    ///  准备其他控件
    private func prepreaOthers() {
        view.addSubview(lengthLabel)
        
        
        // TODO: 要修改
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -320))
    }
    
    
    ///  设置toolbar
    
    private func prepareToolBar() -> UIToolbar {
    
        let toolBar = UIToolbar(frame: CGRectMake(0, 0, 0, 44))
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        

        for settings in itemSettings {
            items.append(UIBarButtonItem(imageName: settings["imageName"]!, highlightedImageName: nil, target: nil, actionName: settings["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()

        toolBar.items = items
        return toolBar
    }
    
    ///设置textview
    private func prepareTextView(){
        
        textView.backgroundColor = UIColor.whiteColor()
        view.addSubview(textView)
        textView.delegate = self
        
        placeHolderLabel.text = "分享新鲜事..."
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.sizeToFit()
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        textView.inputAccessoryView = prepareToolBar()
        textView.ff_Fill(view)
    
    }
    ///  设置导航栏
    private func prepareNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRectMake(0, 0, 100, 32))
        titleView.backgroundColor = UIColor.clearColor()
        let label1 = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
        label1.text = "发送微博"
        let label2 = UILabel(color: UIColor(white: 0, alpha: 0.5), fontSize: 12)
        label2.text = "拉库大王"
        
        titleView.addSubview(label1)
        titleView.addSubview(label2)
        
        label1.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        label2.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView

    }
    // MARK: 懒加载
    private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var textView = UITextView()
    private lazy var lengthLabel = UILabel(color: UIColor.redColor(), fontSize: 12)

}
